﻿using Application.DTO;
using Application.DTO.Department;
using Application.DTO.Permission;
using Application.IService.Department;
using AutoMapper;
using Domain.Entity.Department;
using Infrastructure.IRepository;
using Infrastructure.IRepository.Department;
using Infrastructure.Repository.Department;
using Infrastructure.Repository.Permission;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Application.Service.Department
{
    public class DepartmentService : BaseService<Departments>, IDepartmentService
    {
        private readonly IDepartmentRepository departmentRepository;
        private readonly IUnitOfWork unitOfWork;
        private readonly IMapper mapper;
        public DepartmentService(IDepartmentRepository departmentRepository, IUnitOfWork unitOfWork, IMapper mapper = null) : base(unitOfWork, departmentRepository)
        {
            this.departmentRepository = departmentRepository;
            this.unitOfWork = unitOfWork;
            this.mapper = mapper;
        }
        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="dto">部门信息</param>
        /// <returns></returns>
        public async Task<ResultDTO<int>> InsertDepartment(DepartmentFormDTO dto)
        {
            await departmentRepository.Insert(mapper.Map<Departments>(dto));
            int h = await unitOfWork.SaveChanges();
            if (h > 0)
            {
                return new ResultDTO<int>(h, Domain.Enum.ResultStatusCode.SUCCESS, "添加成功");
            }
            else
            {
                return new ResultDTO<int>(h, Domain.Enum.ResultStatusCode.HANDLEFAIL, "添加失败");
            }
        }
        /// <summary>
        /// 修改部门
        /// </summary>
        /// <param name="dto">修改部门</param>
        /// <returns></returns>
        public async Task<ResultDTO<int>> UpdateDepartment(DepartmentFormDTO dto)
        {
            await departmentRepository.Update(mapper.Map<Departments>(dto));
            int h = await unitOfWork.SaveChanges();
            if (h > 0)
            {
                return new ResultDTO<int>(h, Domain.Enum.ResultStatusCode.SUCCESS, "修改成功");
            }
            else
            {
                return new ResultDTO<int>(h, Domain.Enum.ResultStatusCode.HANDLEFAIL, "修改失败");
            }
        }
        /// <summary>
        /// 逻辑删除部门
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        public async Task<ResultDTO<int>> SortDeleteDepartment(string ids)
        {
            //分割ID值
            string[] temp = ids.Split(',');
            int[] arrayIds = Array.ConvertAll<string, int>(temp, int.Parse);
            foreach (var item in arrayIds)
            {
                //查询部门
                var m =await (await departmentRepository.GetAll()).Where(m => m.IsDeleted == false && m.Id == item).FirstOrDefaultAsync();
                if (m != null)
                {
                    //修改
                    m.IsDeleted = true;
                    departmentRepository.Update(m);
                }
            }

            //保存
            int h = await unitOfWork.SaveChanges();
            if (h > 0)
            {
                return new ResultDTO<int>(h, Domain.Enum.ResultStatusCode.SUCCESS, "删除成功");
            }
            else
            {
                return new ResultDTO<int>(h, Domain.Enum.ResultStatusCode.HANDLEFAIL, "删除失败");
            }
        }
        /// <summary>
        /// 查询部门列表
        /// </summary>
        /// <param name="name">部门名称</param>
        /// <returns></returns>
        public async Task<ResultDTO<List<DepartmentShowDTO>>> SearchDepartment(string name,int pid)
        {
            //查询部门信息
            var list = (await departmentRepository.GetAll());
            if(!string.IsNullOrEmpty(name))
            {
                list = list.Where(x => x.Name.Contains(name));
            }

            var data = Recursion(list.ToList(), pid);
            //返回数据
            return new ResultDTO<List<DepartmentShowDTO>>(data);
        }
        /// <summary>
        /// 递归子方法体
        /// </summary>
        /// <param name="list">所有数据</param>
        /// <param name="pid">上级ID</param>
        /// <returns></returns>
        private List<DepartmentShowDTO> Recursion(List<Departments> list, int pid)
        {
            //获取数据
            var data = list.Where(m => m.IsDeleted==false && m.Pid == pid).OrderByDescending(m=>m.OrderSort).ToList();

            //定义返回值
            List<DepartmentShowDTO> dtos = new List<DepartmentShowDTO>();

            data.ForEach(e =>
            {
                dtos.Add(new DepartmentShowDTO
                {
                    Id = e.Id,
                    Name = e.Name,
                    Describe = e.Describe,
                    IsEnable = (bool)e.IsEnable,
                    LayerIds = Array.ConvertAll<string,int>(e.LayerIds.Split(','),int.Parse),
                    OrderSort = (int)e.OrderSort,
                    Principal = e.Principal,
                    children=Recursion(list,e.Id)
                });
            });

            return dtos.Count() > 0 ? dtos : null;
        }


      


    }
}
